package it.getta.vicinometro.popup;

import it.getta.vicinometro.ActivityCallBack;
import it.getta.vicinometro.R;
import it.getta.vicinometro.adapter.LazyAdapter;
import it.getta.vicinometro.model.PhotoItem;
import it.getta.vicinometro.model.PlaceDetail;
import it.getta.vicinometro.model.PlaceDetailGalleryResult;
import it.getta.vicinometro.model.PlaceDetailResult;
import it.getta.vicinometro.places.NetworkListener;
import it.getta.vicinometro.places.NetworkManager;
import it.getta.vicinometro.utils.FileCache;

import java.io.IOException;

import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.TextView;
 
import com.google.api.client.http.HttpResponseException;

public class InfoPopup extends VicinometroPopup {
	
	private TextView mName;
	private TextView mTypes;
	private TextView mAddress;
	private TextView mPhone;
	private TextView mLatitude;
	private TextView mLongitude;
	private TextView mUrl;
	private TextView mEmptyView;
	
	private Gallery mGallery;
	private LazyAdapter mAdapter;
	
	private String mReference;
	private FileCache mFileCache;

	public InfoPopup(Context context, ActivityCallBack activityCallBack, String placeReference, FileCache fileCache) {
		super(context, activityCallBack, R.layout.info_popup);
		mReference = placeReference;
		mFileCache = fileCache;
	}

	@Override
	public void showPopup() {
		super.showPopup();
		mName = (TextView)mPopupRootView.findViewById(R.id.info_popup_title);
		mTypes = (TextView)mPopupRootView.findViewById(R.id.place_types);
		mAddress = (TextView)mPopupRootView.findViewById(R.id.place_address);
		mPhone = (TextView)mPopupRootView.findViewById(R.id.place_phone);
		mLatitude = (TextView)mPopupRootView.findViewById(R.id.place_latitude);
		mLongitude = (TextView)mPopupRootView.findViewById(R.id.place_longitude);
		mUrl = (TextView)mPopupRootView.findViewById(R.id.place_url);
		mGallery = (Gallery)mPopupRootView.findViewById(R.id.info_popup_gallery);
		mEmptyView = (TextView)mPopupRootView.findViewById(R.id.info_popup_gallery_empty_view);
		
		mAdapter = new LazyAdapter(mContext, mFileCache);
		mGallery.setAdapter(mAdapter);
		mGallery.setEmptyView(mEmptyView);
		mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long lpos) {
				
				mActivityCallBack.startFullscreenGallery(mAdapter.getData(), mGallery.getSelectedItemPosition());
				
			}
		});
		mEmptyView.setText(R.string.finding_images);
		
		fillDetails();
		
	}
	
	private void fillDetails() {
		NetworkManager.getInstance().getPlaceDetailTask(mReference, new NetworkListener() {
			
			public void getPlacesDetailPerformed(final PlaceDetailResult placeDetailResult) {
				
				final PlaceDetail placeDetail = placeDetailResult.getResult();
				
				//fill gallery
				getGalleryItems(placeDetailResult);
				
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						setLabel(mName, placeDetail.getName());
						setLabel(mAddress, placeDetail.getFormattedAddress());
						setLabel(mPhone, placeDetail.getFormattedPhoneNumber());
						setLabel(mLatitude, "" + placeDetail.getGeometry().getLocation().getLat());
						setLabel(mLongitude, "" + placeDetail.getGeometry().getLocation().getLng());
						setLabel(mUrl, "" + placeDetail.getUrl());
						StringBuilder sBuilder = new StringBuilder("");
						if (placeDetail.getTypes() != null) {
							for (int i = 0; i < placeDetail.getTypes().length; i++) {
								if (i < placeDetail.getTypes().length - 1) {
									sBuilder.append(placeDetail.getTypes()[i]
											+ ", ");
								} else {
									sBuilder.append(placeDetail.getTypes()[i]);
								}

							}
						}
						setLabel(mTypes, sBuilder.toString());
						show(mActivityCallBack.getPopupAnchor());
						
					}
				});
				mActivityCallBack.hideAsyncLoading();
				
			}
			
			@Override
			public void getPlacesDetailFailed(int statusCode) {
				mActivityCallBack.hideAsyncLoading();
				showNetworkMessage();
			}
			
			@Override
			public void getPlacesDetailFailed(HttpResponseException hre) {
				mActivityCallBack.hideAsyncLoading();
				showNetworkMessage();
				hre.printStackTrace();
			}
			
			@Override
			public void getPlacesDetailFailed(IOException ioe) {
				mActivityCallBack.hideAsyncLoading();
				showNetworkMessage();
				ioe.printStackTrace();
			}
			
			private void showNetworkMessage() {
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						mActivityCallBack.showNetworkAlert();
					}
				});
				
			}
		});
	}
	
	private void getGalleryItems(PlaceDetailResult placeDetailResult) {
		NetworkManager.getInstance().getPlaceDetailGalleryTask(placeDetailResult.getResult().getName(), 
				"" + placeDetailResult.getResult().getGeometry().getLocation().getLat(), 
				"" + placeDetailResult.getResult().getGeometry().getLocation().getLng(),
				new NetworkListener() {
			
			@Override
			public void getPlacesDetailGalleryPerformed(final PlaceDetailGalleryResult placeDetailGalleryResult) {
				for(int i=0; i<placeDetailGalleryResult.getPhotos().getPhoto().length; i++) {
					System.out.println("" + placeDetailGalleryResult.getPhotos().getPhoto()[i].toString());
				}
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						mAdapter.setData(composeSmallImagePathsArray(placeDetailGalleryResult));
						mAdapter.notifyDataSetChanged();
					}
				});
			}
			
			@Override
			public void getPlacesDetailGalleryFailed(int statusCode) {
				manageNoImages();
			}
			
			@Override
			public void getPlacesDetailGalleryNoImages() {
				manageNoImages();
			}
			
			@Override
			public void getPlacesDetailGalleryFailed(HttpResponseException hre) {
				hre.printStackTrace();
				manageNoImages();
			}
			
			@Override
			public void getPlacesDetailGalleryFailed(IOException ioe) {
				ioe.printStackTrace();
				manageNoImages();
			}
			
			private void manageNoImages() {
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						mEmptyView.setText(R.string.no_images_available);
					}
				});
			}
		});
	}
	
	private String[] composeSmallImagePathsArray(PlaceDetailGalleryResult results) {
		//http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
		PhotoItem[] photos = results.getPhotos().getPhoto();
		String[] paths = new String[photos.length];
		for(int i=0; i<photos.length; i++) {
			StringBuilder sBuilder = new StringBuilder("http://farm");
			PhotoItem photo = photos[i];
			sBuilder.append(photo.getFarm()).
				append(".staticflickr.com/").
				append(photo.getServer()).
				append("/").
				append(photo.getId()).
				append("_").
				append(photo.getSecret()).
				append("_t").
				append(".jpg");
			paths[i] = sBuilder.toString();
		}
		
		return paths;
		
	}
	
	private void setLabel(TextView view, String label) {
		if(label != null && label.trim().length() > 0) {
			view.setText(label);
		} else {
			view.setText(" - ");
		}
	}
	
}
